package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.FEED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 *
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IFollowService followService;

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            this.queryBlogUser(blog);
            //判断当前用户是否点赞过，赋值给isLike字段
            this.isBlogLiked(blog);
        });

        return Result.ok(records);
    }

    @Override
    public Result queryBlogById(Long id) {
        //查询blog
        Blog blog = getById(id);
        if (blog==null){
            return Result.fail("笔记不存在");
        }
        //查询blog有关的用户
        queryBlogUser(blog);
        //判断当前用户是否点赞过，赋值给isLike字段
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    //bug:用户未登录不需要查询是否点过赞
    private void isBlogLiked(Blog blog) {
        //获取登录用户
        UserDTO user = UserHolder.getUser();
        if (user==null){
            //解决bug:用户未登录不需要查询是否点过赞
            return;
        }
        Long userId = user.getId();
        //判断当前登录用户是否点赞过
        String key = BLOG_LIKED_KEY+blog.getId();
        //Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
//        blog.setIsLike(BooleanUtil.isTrue(isMember));
        blog.setIsLike(score!=null);
    }

    @Override
    public Result likeBlog(Long id) {
        //获取登录用户
        Long userId = UserHolder.getUser().getId();
        //判断当前登录用户是否点赞过
        String key = BLOG_LIKED_KEY+id;
        //set方式
        //Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        //zset方式，用score,存在则返回分数，不存在则返回null
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());

        //if (BooleanUtil.isFalse(isMember)){  //返回值是包装类，可能为空
        if (score== null){
            //如果没点赞，可以点赞
            //数据库点赞数+1
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            if (isSuccess){//数据库更新成功才更新redis
                //保存用户到redis集合
                //stringRedisTemplate.opsForSet().add(key,userId.toString());
                //保存到sortedSet,分数用时间戳，时间戳越小，表示越早点赞 zadd key value score
                stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());
            }

        }else {
            //如果点赞过，取消点赞
            //数据库点赞数-1
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            //把用户从redis的set集合中删除
            if (isSuccess){//数据库更新成功才更新redis
                //删除
                //stringRedisTemplate.opsForSet().remove(key,userId.toString());
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
            }
        }

        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {
        String key = BLOG_LIKED_KEY+id;
        //查询top5的点赞用户，zrang key 0 4
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (top5==null||top5.isEmpty()){//避免空指针
            return Result.ok(Collections.emptyList());
        }
        //解析出其中的用户id,stream流，取出set的value封装到list
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr = StrUtil.join(",", ids);

        //这里点赞的顺序跟数据库查的顺序in(5,1)不一致，会默认变成有序(1,5)，要用order by field(id,5,1)
        //根据用户id查询用户  where id in(5,1) order by field(id,5,1)
        List<UserDTO> userDTOS = userService
                .query().in("id",ids).last("ORDER BY FIELD(id,"+idStr+")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOS);
    }

    //基于退模式实现关注推送功能
    //修改新增探店笔记的业务，在保存blog到数据库的同时，推送到粉丝的收件箱
    //收件箱满足可以根据时间戳排序，必须用redis的数据结构
    //查询收件箱数据时，可以实现分页查询
    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();

        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSuccess = save(blog);
        if (!isSuccess){
            return Result.fail("新增失败");
        }

        //推送给粉丝
        //查询笔记作者的粉丝  去用户粉丝关系中间表查，follow_user_id是被关注的id,就是查follow_user_id=？的所有用户id
        //select * from tb_follow where follow_user_id=?
        List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();

        //推送笔记id给所有粉丝
        for (Follow follow : follows) {
            //获取粉丝id
            Long userId = follow.getUserId();
            //推送，每个粉丝都有一个收件箱，而收件箱都是一个sortedSet，key是粉丝id,value是blog的id，score是时间戳
            String key = FEED_KEY + userId;
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
        }

        // 返回id
        return Result.ok(blog.getId());

    }

    //max:lastId:当前时间戳|上一次查询的最小时间戳
    //offset：0|再上一次结果中，与最小值一样的元素个数
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //获取当前用户
        Long userId = UserHolder.getUser().getId();
        //滚动分页查询收件箱 zrevrangebyscore key max min withscores limit offset count
        String key = FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        //判空
        if (typedTuples==null||typedTuples.isEmpty()){
            return Result.ok();
        }
        //解析数据：blogId,minTime时间戳，offset
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int os  = 1;
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {//5 4 4 2 2
            //获取id
            ids.add(Long.valueOf(tuple.getValue()));

            //获取分数时间戳，遍历完最是最小时间
            long time = tuple.getScore().longValue();
            //获取offset
            if (time==minTime){
                os++;//等于最小时间，则加1
            }else {
                minTime = time;//不等于最小时间肯定比最小时间小，就把当前赋值给最小时间
                os=1;//重置offset
            }

        }
        String idStr = StrUtil.join(",",ids);
        //根据id查询blog
        List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();

        for (Blog blog : blogs) {
            //查询blog有关的用户
            queryBlogUser(blog);
            //判断当前用户是否点赞过，赋值给isLike字段
            isBlogLiked(blog);
        }

        //封装返回
        ScrollResult r = new ScrollResult();
        r.setList(blogs);
        r.setMinTime(minTime);
        r.setOffset(os);

        return Result.ok(r);
    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
